<?php

namespace App\Http\Controllers;

use App\Channel;
use App\Filters\ThreadFilters;
use App\Inspections\Spam;
use App\Thread;
use App\Trending;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ThreadsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function __construct()
    {
//        $this->middleware('auth')->only('store'); // 白名单，意味着仅 store 方法需要登录
        $this->middleware('auth')->except(['index','show']); // 黑名单，意味着除了 index、show 方法外，其他方法需要登录
    }

    public function index(Channel $channel,ThreadFilters $filters,Trending $trending)
    {
        //
//        if($channel->exists){
//
//            /*$channelId = Channel::where('slug',$channelSlug)->first()->id;
//            $threads =Thread::where('channel_id',$channelId)->latest()->get();*/
//
//            $threads = $channel->threads()->latest();
//
//        }else{
//            $threads = Thread::latest();
//        }
//
//        if($username = request('by')){
//            $user = \App\User::where('name',$username)->firstOrFail();
//            $threads->where('user_id',$user->id);
//
//        }
//
//        $threads = $threads->get();
        $threads = $this->getThreads($channel,$filters);
        if(request()->wantsJson()){
            return $threads;
        }

//        $trending = array_map('json_decode',Redis::zrevrange('trending_threads',0,4));
//
//         return view('threads.index',compact('threads','trending'));

        return view('threads.index',[
            'threads' => $threads,
            'trending' => $trending->get()
        ]);


    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('threads.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,Spam $spam)
    {
        //
//      exists:table,column  验证的字段必须存在于给定的数据库表中
//        if(! auth()->user()->confirmed){
//            return redirect('/threads')->with('flash','You must first confirm your eamil address.');
//        }

        $this->validate($request,[
            'title' => 'required|spamfree',
            'body' => 'required|spamfree',
            'channel_id' => 'required|exists:channels,id'
        ]);

        $thread = Thread::create([
            'user_id' => auth()->id(),
            'channel_id' => request('channel_id'),
            'title' => request('title'),
            'body' => request('body'),
        ]);

        return redirect($thread->path())
            ->with('flash','Your thread has been published!');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Thread  $thread
     * @return \Illuminate\Http\Response
     */
    public function show($channelId,Thread $thread,Trending $trending)
    {
        //
        /*$replies = $thread->replies()->paginate(10);
        return view('threads.show',compact('thread','replies'));*/
        if(auth()->check()){
            auth()->user()->read($thread);
        }

        /*Redis::zincrby('trending_threads',1,json_encode([
            'title' => $thread->title,
            'path' => $thread->path()
        ]));*/


        $trending->push($thread);

//        $thread->recordVisit();
        $thread->visits()->record();
        return view('threads.show',compact('thread'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Thread  $thread
     * @return \Illuminate\Http\Response
     */
    public function edit(Thread $thread)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Thread  $thread
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Thread $thread)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Thread  $thread
     * @return \Illuminate\Http\Response
     */
    public function destroy($channel,Thread $thread)
    {
        //
//        $thread->replies()->delete();

        /*if($thread->user_id != auth()->id()){
            if(request()->wantsJson()){
                return response(['status' => 'Permission Denied'],403);
            }

            return redirect('/login');
        }*/

        /*if($thread->user_id != auth()->id()){
            abort(403,"You don't have permission to do this.");
        }*/

        $this->authorize('update',$thread);
        
        $thread->delete();
        if(request()->wantsJson()) {
            return response([], 204);
        }
        return redirect('/threads');
    }

    protected function getThreads(Channel $channel, ThreadFilters $filters)
    {
//        $threads = Thread::with('channel')->latest()->filter($filters);
        /**因为在Thread.php定义了
        protected $with = ['creator', 'channel'];
        所以ThreadController.php里对getThreads方法去掉with*/

        $threads = Thread::with('channel')->latest()->filter($filters);

        if($channel->exists){
//            $threads = $channel->threads()->latest();
            $threads->where('channel_id',$channel->id);
        }

//        $threads = $threads->filter($threadFilters)->get();
//        dd($threads->toSql());
//        $threads = $threads->get();
        $threads = $threads->paginate(20);

        return $threads;

    }
}
